package com.laboratory.servicecustomer.workBench.controller;

import com.Laboratory.utilPojo.projectWithState;
import com.Laboratory.utilPojo.projectWithUrl;
import com.Laboratory.workBench.pojo.file;
import com.Laboratory.workBench.pojo.project;
import com.Laboratory.workBench.pojo.teacher;
import com.Laboratory.workBench.service.projectService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.laboratory.servicecustomer.constant.constantArgs;
import com.laboratory.servicecustomer.util.UuidUtil;
import com.laboratory.servicecustomer.util.fileUtil;
import com.laboratory.servicecustomer.utilPojo.comm;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Author acok
 * @description:TODO
 * @Date 2022/12/25 9:35
 * @Version 1.0
 */
@Controller
@RequestMapping("/project")
public class projectController {
    @DubboReference(interfaceClass = projectService.class,version = "1.0.0")
    private projectService projectService;
          /**
               * @return: 教师实例列表
               * @param: 无参数
               * @description: 获取教师实例列表供项目申请时选择
               * @Author: Acok
               * @mbggenerated 2022/12/30
               */
    @RequiresRoles(value = {"users","admin","Root"},logical = Logical.OR)
    @RequiresPermissions(value = {"users:projectApply","admin:projectApply","Root:highest"},logical = Logical.OR)
    @GetMapping("/getTeacherListByProject")
    @ResponseBody
    public Object getTeacherListByProject(){
        comm comm=new comm();
        try{
            List<teacher> teachers = projectService.getTeacherListByApply();
            comm.setCode(constantArgs.COMMUNITY_SUCCESS_CODE);
            comm.setMessage(constantArgs.COMMUNITY_SUCCESS_MESSAGE);
            comm.setOther(teachers);
        }catch(Exception e){
            e.printStackTrace();
            comm.setCode(constantArgs.COMMUNITY_FAIL_CODE);
            comm.setMessage(constantArgs.COMMUNITY_FAIL_MESSAGE);
        }
        return comm;
    }

          /**
               * @return: 前后端交互实例
               * @param: 项目实例对象（JSON）、附件1、附件2
               * @description: 为了同时接收实例对象以及文件，将前端文件转化为json字符串同二进制文件一同传递
               * @Author: Acok
               * @mbggenerated 2022/12/30
               */
    @RequiresRoles(value = {"users","admin","Root"},logical = Logical.OR)
    @RequiresPermissions(value = {"users:projectApply","admin:projectApply","Root:highest"},logical = Logical.OR)
    @PostMapping("/createProjectApply")
    @ResponseBody
    public Object insertProjectApply( @RequestParam("applyInformation") String applyInformation,
                                      MultipartFile proIntroduce,MultipartFile teamIntroduce){
        comm comm=new comm();
        try {
            project project = JSON.parseObject(applyInformation, new TypeReference<project>() {
            });
            if (projectService.insertProjectApply(project)>0) {
                List<file> fileList=new ArrayList<>();
                //获取文件保存url
                String proUrl= fileUtil.SaveFileToLocal(proIntroduce);
                String teamUrl= fileUtil.SaveFileToLocal(teamIntroduce);
                //保存成功则修改数据库
                if (!"false".equals(proUrl)||!"false".equals(teamUrl)){
                    //记录主键
                    String proIntroduceId=UuidUtil.getUUIDById();
                    String teamIntroduceId=UuidUtil.getUUIDById();
                    //file实例
                    fileList.add(new file(proIntroduceId,proIntroduce.getOriginalFilename(),proUrl,project.getId()));
                    fileList.add(new file(teamIntroduceId,teamIntroduce.getOriginalFilename(),teamUrl,project.getId()));
                    //保存成功
                    if(projectService.saveFileToLocalService(fileList)>0){
                        List<projectWithUrl> list=new ArrayList<>();
                        //生成两个实体类插入到缓存中
                        projectWithUrl projectWithUrl=new projectWithUrl(project.getId(),
                                project.getProjectname(),
                                proIntroduceId,
                                proIntroduce.getOriginalFilename(),
                                proUrl);
                        list.add(projectWithUrl);
                        projectWithUrl projectWithUrl1=new projectWithUrl(project.getId(),
                                project.getProjectname(),
                                teamIntroduceId,
                                teamIntroduce.getOriginalFilename(),
                                teamUrl);
                        list.add(projectWithUrl1);
                        projectService.updateRedisCacheByInsertApply(list);
                    }
                    comm.setCode(constantArgs.COMMUNITY_SUCCESS_CODE);
                    comm.setMessage(constantArgs.COMMUNITY_SUCCESS_MESSAGE);
                }else {
                    comm.setCode(constantArgs.COMMUNITY_FAIL_CODE);
                    comm.setMessage(constantArgs.COMMUNITY_FILE_FAIL_MESSAGE);
                }
            }else {
                comm.setCode(constantArgs.COMMUNITY_FAIL_CODE);
                comm.setMessage(constantArgs.COMMUNITY_FAIL_MESSAGE);
            }
        }catch (Exception e){
            e.printStackTrace();
            comm.setCode(constantArgs.COMMUNITY_FAIL_CODE);
            comm.setMessage(constantArgs.COMMUNITY_FAIL_MESSAGE);
        }
        return comm;
    }


          /**
               * @return: 项目统计数据
               * @param: 无参数
               * @description: 获取有关项目统计数据传递至前端进行显示
               * @Author: Acok
               * @mbggenerated 2022/12/30
               */
    @RequiresRoles(value = {"users","admin","Root"},logical = Logical.OR)
    @RequiresPermissions(value = {"users:projectStatistics","admin:projectStatistics","Root:highest"},logical = Logical.OR)
    @GetMapping("/getTeacherPopularityData")
    @ResponseBody
    public Object getTeacherPopularityData(){
        comm comm=new comm();
        try{
            List<Map<Object, Object>> mapList = projectService.getTeacherPopularity();
            comm.setCode(constantArgs.COMMUNITY_SUCCESS_CODE);
            comm.setMessage(constantArgs.COMMUNITY_SUCCESS_MESSAGE);
            comm.setOther(mapList);
        }catch (Exception e){
            e.printStackTrace();
            comm.setCode(constantArgs.COMMUNITY_FAIL_CODE);
            comm.setMessage(constantArgs.COMMUNITY_FAIL_MESSAGE);
        }
        return comm;
    }
    @RequiresRoles(value = {"users","admin","Root"},logical = Logical.OR)
    @RequiresPermissions(value = {"users:projectStatistics","admin:projectStatistics","Root:highest"},logical = Logical.OR)
    @GetMapping("/getCostRankData")
    @ResponseBody
    public Object getCostRankData(){
        comm comm=new comm();
        try{
            List<Map<Object, Object>> mapList = projectService.getCostRankData();
            comm.setCode(constantArgs.COMMUNITY_SUCCESS_CODE);
            comm.setMessage(constantArgs.COMMUNITY_SUCCESS_MESSAGE);
            comm.setOther(mapList);
        }catch(Exception e){
            e.printStackTrace();
            comm.setCode(constantArgs.COMMUNITY_FAIL_CODE);
            comm.setMessage(constantArgs.COMMUNITY_FAIL_MESSAGE);
        }
        return comm;
    }
    @RequiresRoles(value = {"users","admin","Root"},logical = Logical.OR)
    @RequiresPermissions(value = {"users:projectStatistics","admin:projectStatistics","Root:highest"},logical = Logical.OR)
    @GetMapping("/getProjectListWithState")
    @ResponseBody
    public Object getProjectListWithState(){
        comm comm=new comm();
        try {
            List<projectWithState> projectList = projectService.getProjectList();
            comm.setCode(constantArgs.COMMUNITY_SUCCESS_CODE);
            comm.setMessage(constantArgs.COMMUNITY_SUCCESS_MESSAGE);
            comm.setOther(projectList);
        }catch (Exception e){
            e.printStackTrace();
            comm.setCode(constantArgs.COMMUNITY_FAIL_CODE);
            comm.setMessage(constantArgs.COMMUNITY_FAIL_MESSAGE);
        }
        return comm;
    }

    @RequiresRoles(value = {"users","admin","Root"},logical = Logical.OR)
    @RequiresPermissions(value = {"users:projectApply","admin:projectApply","Root:highest"},logical = Logical.OR)
    @GetMapping("/downloadFileTemplate")
    @ResponseBody
    public void downloadFileTemplate(
            @RequestParam("fileType")String fileType,
            HttpServletResponse response
    ){
        OutputStream outWeb=null;
        HSSFWorkbook wb=null;
        try {
            /*写入服务器*/
            wb = new HSSFWorkbook();
            //创建数据表
            HSSFSheet sheet = wb.createSheet(constantArgs.TEMPLATE_FILE_NAME);
            //创建首行
            HSSFRow row = sheet.createRow(0);
            switch (fileType){
                case constantArgs.FILE_TEAM_TYPE:{
                    //团队简介
                    //创建首行首单元格
                    HSSFCell cell = row.createCell(0);
                    cell.setCellValue("姓名");
                    cell = row.createCell(1);
                    cell.setCellValue("学号");
                    cell = row.createCell(2);
                    cell.setCellValue("班级");
                    cell = row.createCell(3);
                    cell.setCellValue("学院");
                    cell = row.createCell(4);
                    cell.setCellValue("备注");

                    break;
                }
                case constantArgs.FILE_PROJECT_TYPE:{
                    //项目简介
                    HSSFCell cell = row.createCell(0);
                    cell.setCellValue("项目名");
                    cell = row.createCell(1);
                    cell.setCellValue("负责人");
                    cell = row.createCell(2);
                    cell.setCellValue("研究方向");
                    cell = row.createCell(3);
                    cell.setCellValue("研究意义");
                    cell = row.createCell(4);
                    cell.setCellValue("是否与其他单位合作？(合作请备注)");
                    cell = row.createCell(5);
                    cell.setCellValue("备注");

                    break;
                }
            }
                /*下载至浏览器*/
                response.setContentType("application/octet-stream;charset=UTF-8");
                response.addHeader("Content-Disposition", "attachment;filename=template.xls");
                outWeb = response.getOutputStream();
                wb.write(outWeb);
                wb.close();
                outWeb.flush();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            fileUtil.closeFileStream(outWeb,wb);
        }
    }
}
